import { defineStore } from 'pinia';
import axios from 'axios';
import { resetPostData } from '@/utils/resetPostData.js';
import { ElMessage } from 'element-plus';
import { getInfo } from '@/http/api/login';
import router from '@/router';
export const userState = defineStore({
	id: 'user',
	state: () => {
		return {
			userInfo: {},
			token: '',
			tokenHead: '',
			menu: [],
			routes: [],
			subApps: [],
			asyncRoutestMark: false
		};
	},
	// 相当于计算属性,利用defineStore()中的getters属性定义，他们接收状态作为第一个参数一鼓励箭头函数使用
	getters: {},
	// 相当于组件中的methods，他们可以使用defineStore()中的actions属性定义，并且它们非常适合定义业务逻辑
	actions: {
		async getToken(params) {
			let _this = this;
			params.grant_type = 'password';
			params.client_id = 'client-app';
			params.client_secret = '123456';
			await axios({
				method: 'post',
				url: import.meta.env.VITE_APP_BASE_API + '/auth/oauth/token',
				data: resetPostData(params)
			}).then(async (res) => {
				if (res && res.status === 200 && res.data.code === 200) {
					_this.token = res.data.data.token;
					_this.tokenHead = res.data.data.tokenHead;
					await _this.getUserInfo();
				} else {
					ElMessage.error(res.data.fail.errMsg);
				}
			});
		},
		//获取菜单信息
		getUserInfo() {
			getInfo().then(() => {
				axios({
					method: 'get',
					url:
						import.meta.env.VITE_APP_BASE_API + '/sys-mgt/sys-mgt/user/getMenuAndRoles',
					headers: {
						Authorization: this.tokenHead + this.token
					}
				}).then((res) => {
					if (res && res.status === 200) {
						this.userInfo = res.data.user;
						this.menu = res.data.menu;
						this.menu.map((m) => {
							m.childs.map((item) =>
								this.subApps.push({
									name: item.name,
									entry: item.href,
									container: '#sub-container',
									activeRule: item.id,
									props: {} // 主应用与子应用通信传值
								})
							);
						});
						this.routes = this.menu.map((route) => ({
							path: route.id,
							name: route.name,
							meta: {
								src: route.href,
								title: route.name,
								iconType: route.iconType
							} // 包含菜单标题等信息
						}));
						console.log('this.subApps', this.subApps);
						router.push('/');
					} else {
						ElMessage.error('获取用户信息失败');
					}
				});
			});
		},
		// 添加动态路由
		addRoutes(newRoutes) {
			this.routes = newRoutes;
		},
		// 清空动态路由和侧边栏路由
		clearRoutes() {
			this.routes = [];
		}
	},
	persist: {
		enabled: true
	}
});
